const express = require('express');
const router = express.Router();
const {Blog, BlogTag} = require('../models/blog');
const {auth} = require('./user');
const multer = require('multer')

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './public/blog');
    },
    filename: function (req, file, cb) {
        const [name, suffix] = file.originalname.split('.');
        cb(null, `${name}_${new Date().getTime()}.${suffix}`);
    }
});
const upload = multer({storage: storage});
// 文章详情
router.get('/detail/:id', async function (req, res, next) {
    try {
        const blogs = JSON.parse(req.cookies.blogs || '[]') // 获取cookie值
        const id = req.params.id // 文章id
        let blog = await Blog.findOne({_id: id}) // 查询单篇文章
        if (!blogs.includes(id)) { // 如果cookie中没有获取到此id，浏览量+1
            blogs.push(id)
            blog.read_num += 1
            await Blog.updateOne({_id: id}, {read_num: blog.read_num})
            res.cookie('blogs', JSON.stringify(blogs), {maxAge: 1000 * 60 * 60 * 12})
        }
        res.render('detail.html', {blog})
    } catch (e) {
        res.render('index.html', {"err": "网络错误"})
    }
});

// 创建博客标签
router.post('/tag', async (req, res, next) => {
    const {tag} = req.body;
    const t = await BlogTag.findOne({blog_tag: tag}) // 在数据库中找标签
    if (t === null) { // 找不到就创建
        const blog = await BlogTag.create({blog_tag: tag}) // 将标签写入数据库
        if (blog._id) {
            return res.json({
                err_code: 0,
                msg: '创建成功'
            })
        } else {
            return res.json({
                err_code: -1,
                msg: '创建失败'
            })
        }
    } else {
        return res.json({
            err_code: -1,
            msg: '标签已存在'
        })
    }
})

// 获取所有标签
router.get('/tag', async (req, res, next) => {
    try {
        const result = await BlogTag.find({}).sort({"create_date": -1})
        return res.json({
            err_code: 0,
            msg: 'success',
            result
        })
    } catch (e) {
        return res.status(500).json({
            err_code: -1,
            msg: '服务器错误',
            result: []
        })
    }
})
// 创建文章
router.post('/create', auth, upload.single('cover'), async (req, res, next) => {
    const {title, content, tag, author} = req.body
    const file = req.file
    const blog = await Blog.create({
        title,
        tag,
        content,
        user: author,
        cover: '\\' + file.path.replace('public\\', '').replace('\\', "/"),
    })
    if (blog._id) {
        return res.json({
            err_code: 0,
            msg: '创建成功',
            data: blog
        })
    } else {
        return res.json({
            err_code: -1,
            msg: '创建失败'
        })
    }
})
// 页码值校验
const pageParamVerify = (req, Page, pageSize, maxPageSize = 30, limitPage = true) => { // page参数校验
    const query = req.query;
    let page_size = Math.ceil(query.page_size * 1) || pageSize;
    let page = Math.max(query.page * 1 || null, Page);
    if (limitPage === true) {
        page = page > 1000 ? 1000 : page // 只能看前1000页
        page_size = page_size > maxPageSize ? pageSize : page_size; // 大于30条，返回10条
    }
    return [page, page_size]
};
// 所有的文章，json格式
router.get('/list', async (req, res) => {
    const search = req.query.search
    const category = req.query.category || 'html'
    const regex = new RegExp(search, 'i');
    let [page, page_size] = pageParamVerify(req, 1, 10);
    const totalCount = await Blog.find({title: {$regex: regex}},).count();
    const blogs = await Blog.find({title: {$regex: regex}},).sort({"create_date": -1}).skip((page - 1) * page_size).limit(page_size).populate('tag').lean();
    if (category === 'html') {
        return res.render('blog_list.html', {blogs, totalCount, currentPage: page, pageSize: page_size})
    } else {
        return res.json({
            err_code: 0,
            total_count: totalCount,
            blogs
        })
    }
})

router.put('/update', auth, upload.single('cover'), async (req, res, next) => {
    const {title, content, tag, author, _id} = req.body
    const file = req.file
    let data = {
        title,
        content,
        tag,
        user: author,
    }
    if (file && file.path) {
        data = Object.assign(data, {
            cover: '\\' + file.path.replace('public\\', '').replace('\\', "/"),
        })
    }
    try {
        const blog = await Blog.updateOne({_id}, {$set:data})
        if (blog) {
            return res.json({
                err_code: 0,
                msg: '更新成功',
            })
        } else {
            return res.json({
                err_code: 0,
                msg: '更新失败',
            })
        }
    } catch (e) {
        console.log(e)
        return res.json({
            err_code: -1,
            msg: '更新失败',
        })
    }
})

module.exports = router;
